import json
import traceback

from flask import Flask, make_response
from flask_cors import CORS
from werkzeug.exceptions import HTTPException

from api.article import app_article
from api.user import app_auth
from api.space import app_wiki
from config.setting import FlaskSettings
from common.exceptions import ApiException
from common.exceptions import UnKnowServerError, CsrfException, ParameterException
from plugin.flask_session_plugin import sess
from loguru import logger

from flask_jwt_extended import JWTManager

jwt = JWTManager()


def create_app():
    app = Flask(__name__, static_folder=FlaskSettings.UPLOAD_FOLDER, static_url_path=FlaskSettings.UPLOAD_PREFIX)
    app.config.from_object(FlaskSettings)

    sess.init_app(app)
    jwt.init_app(app)
    # 注册子应用
    app.register_blueprint(app_auth)
    app.register_blueprint(app_wiki)
    app.register_blueprint(app_article)
    # 跨域
    CORS(app, resources={r"/api/*": {"origins": ["http://localhost:3031", "https://www.yugongcoding.com"]}},
         supports_credentials=True)
    return app


app = create_app()


# 全局错误AOP处理
@app.errorhandler(Exception)
def framework_error(e):
    logger.error(e)
    if isinstance(e, ApiException):
        return e.get_body()
    if isinstance(e, HTTPException):
        return ApiException(msg=e.description, error_code=e.code).get_body()
    else:
        if not app.config['DEBUG']:
            return UnKnowServerError().get_body()
        else:
            return e


# @app.after_request
# def after_req(resp):
#     resp = make_response(resp)
#     data = json.loads(resp.data)
#     if "errors" in data:
#         logger.error(data)
#         resp.status_code = 200
#         resp.data = ParameterException(msg=data.get('message'), data=data.get('errors')).get_body()
#     return resp


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5005, debug=False)
